import pygame
import sys
import os
from utils.config import SCREEN_WIDTH, SCREEN_HEIGHT, BG_IMAGE, FONT_NAME

LEADERBOARD_FILE = "save.txt"
MAX_ENTRIES = 9
def read_leaderboard():
    if not os.path.exists(LEADERBOARD_FILE):
        return []
    with open(LEADERBOARD_FILE, "r") as f:
        lines = f.readlines()
    return [int(line.strip()) for line in lines if line.strip().isdigit()]

def write_leaderboard(scores):
    with open(LEADERBOARD_FILE, "w") as f:
        for score in scores[:MAX_ENTRIES]:
            f.write(f"{score}\n")

def update_leaderboard(new_score):
    scores = read_leaderboard()
    scores.append(new_score)
    scores = sorted(scores, reverse=True)[:MAX_ENTRIES]
    write_leaderboard(scores)

class LeaderboardInterface:
    def __init__(self, bg_image_filename=None, position=None, size=None):
        pygame.init()
        self.width = size[0] if size else SCREEN_WIDTH
        self.height = size[1] if size else SCREEN_HEIGHT
        if position:
            os.environ['SDL_VIDEO_WINDOW_POS'] = f"{position[0]},{position[1]}"
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption("Snake Game - Leaderboard")
        self.font = pygame.font.SysFont(FONT_NAME, 40)  # Smaller font
        self.small_font = pygame.font.SysFont(FONT_NAME, 28)
        self.bg_image = None
        image_file = bg_image_filename if bg_image_filename else BG_IMAGE
        if image_file:
            assets_path = os.path.join(os.path.dirname(__file__), '..', 'assets')
            image_path = os.path.join(assets_path, image_file)
            if os.path.exists(image_path):
                self.bg_image = pygame.image.load(image_path)
                self.bg_image = pygame.transform.scale(self.bg_image, (self.width, self.height))
        self.scores = read_leaderboard()

    def show(self):
        running = True
        while running:
            if self.bg_image:
                self.screen.blit(self.bg_image, (0, 0))
            else:
                self.screen.fill((0, 0, 0))

            title_surface = self.font.render("Leaderboard", True, (255, 255, 0))
            title_rect = title_surface.get_rect(center=(self.width // 2, 60))
            self.screen.blit(title_surface, title_rect)

            for i, score in enumerate(self.scores[:MAX_ENTRIES]):
                score_surface = self.small_font.render(f"{i+1}. {score}", True, (255, 255, 255))
                score_rect = score_surface.get_rect(center=(self.width // 2, 120 + i * 40))
                self.screen.blit(score_surface, score_rect)

            tip_surface = self.small_font.render("Press any key to return", True, (255, 255, 0))
            tip_rect = tip_surface.get_rect(center=(self.width // 2, self.height - 40))
            self.screen.blit(tip_surface, tip_rect)

            pygame.display.flip()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN or (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1):
                    pygame.time.delay(200)
                    return